package middleware

import (
	"github.com/sirupsen/logrus"
	"net/http"
	"time"
)

type Middleware struct {
	Logger *logrus.Logger
}

func NewMiddleware(logger *logrus.Logger) *Middleware {
	return &Middleware{Logger: logger}
}

func (m *Middleware) CORSMiddleware(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func (m *Middleware) SignMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var err error
		accessSign := &Signature{}
		accessSign.AppKey = r.Header.Get("AppKey")
		accessSign.Nonce = r.Header.Get("Nonce")
		accessSign.CheckSum = r.Header.Get("CheckSum")
		accessSign.CurTime = r.Header.Get("CurTime")
		if err = accessSign.CheckSignature(); err != nil {
			w.WriteHeader(http.StatusForbidden)
			_, _ = w.Write([]byte(err.Error()))
			return
		}
		next.ServeHTTP(w, r)
	})
}

func (m *Middleware) LoggingMiddleware(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		t1 := time.Now()
		next.ServeHTTP(w, r)
		t2 := time.Now()
		if nil != m.Logger {
			m.Logger.Printf("[%s] %q %v", r.Method, r.URL.String(), t2.Sub(t1))
		}
	}
	return http.HandlerFunc(fn)
}

func (m *Middleware) RecoverMiddleware(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				if nil != m.Logger {
					m.Logger.Printf("Recover from panic: %+v", err)
				}
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}
